var app = getApp();
var getToken = function() {
  var tokens = wx.getStorageSync('token') || '';
  var token = '';
  if (tokens != '') {
    token = tokens;
  } else {
    // wx.showToast({
    //   title: '缺少token',
    // });
  }
  return token
}

var refreshToken = function() {
  let refreshToken = wx.getStorageSync('refreshToken')
  wx.removeStorageSync('token')
  if (!refreshToken) {
    return;
  }
  return http.get('http://127.0.0.1:9000/login/refreshAccessToken', {
    refreshToken
  })
}

let request = function(url, method, data = {}, header = {}) {
  header = Object.assign({}, {
    'content-type': 'application/json',
    'Authorization': getToken()
  }, header);
  wx.showLoading({
    title: '正在加载中'
  });
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data,
      method,
      header,
      success: function(res) {
        if (res.data.code == 100) {
          resolve(res);
          // token超时 需要刷新
        } else if (res.data.code == 201) {
          refreshToken().then((r) => {
            if (r.data.code == 100) {
              wx.setStorage('token', r.data.data)
              request(url, method, data, header).then(result => {
              resolve(result);
            }).catch(e => {
              reject(e);
            })
            } else {
              reject(res)
            }
          }).catch(e => {
            reject(res)
          })
        } else {
          reject(res)
        }
        wx.hideLoading();
      },
      fail: function(e) {
        reject(e)
        wx.hideLoading();
      }
    })
  })
}

let http = {
  post: function(url, obj = {}) {
    return request(url, 'POST', obj, {
      'content-type': 'application/x-www-form-urlencoded'
    })
  },
  get: function(url, obj = {}) {
    return request(url, 'GET', obj, {
      'content-type': 'application/json'
    })
  }
}
export default http;